package club.janna.study.spring.context;


import club.janna.study.spring.annotation.JannaComponent;
import club.janna.study.spring.util.ClassUtil;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class JannaAnnotationApplicationContext {
    private final Map<String, Object> singletonMap = new ConcurrentHashMap<>();
    private final String basePackage;

    public JannaAnnotationApplicationContext(String basePackage) {
        this.basePackage = basePackage;
    }

    /**
     * 通过名称获取bean
     * @param name
     * @param <T>
     * @return
     */
    public <T> T getBean(String name) {
        if(singletonMap.containsKey(name))
            return (T) singletonMap.get(name);
        try {
            return (T) doCreateBean(name);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 创建bean
     * @param name
     * @return
     */
    public Object doCreateBean(String name) throws Exception {
        Object o = null;
        List<Class<?>> classes = ClassUtil.getAllClassByPackageName(Package.getPackage(basePackage));
        for (Class<?> aClass : classes) {
            if(aClass == null || aClass.getAnnotation(JannaComponent.class) == null)
                continue;
            Object o1 = aClass.newInstance();
            String id = aClass.getSimpleName();
            id = id.substring(0, 1).toLowerCase() + id.substring(1);
            singletonMap.put(id, o1);
            if(name.equals(id))
                o = o1;
        }
        return o;
    }
}
